package cn.starrysky.hrm.service.impl;

import cn.starrysky.hrm.client.LoginUserClient;
import cn.starrysky.hrm.domain.Employee;
import cn.starrysky.hrm.domain.LoginUser;
import cn.starrysky.hrm.domain.Tenant;
import cn.starrysky.hrm.dto.EnteringDto;
import cn.starrysky.hrm.exception.GlobalException;
import cn.starrysky.hrm.mapper.EmployeeMapper;
import cn.starrysky.hrm.mapper.TenantMapper;
import cn.starrysky.hrm.query.TenantQuery;
import cn.starrysky.hrm.service.ITenantService;
import cn.starrysky.hrm.util.AjaxResult;
import cn.starrysky.hrm.util.PageList;
import cn.starrysky.hrm.utils.ValidUtils;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author starrysky
 * @since 2021-03-02
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginUserClient loginUserClient;

    @Override
    public PageList<Tenant> selectPageList(TenantQuery query) {
        //分页条件
        Page<Tenant> tenantPage = new Page<>(query.getPage(), query.getRows());
        //查询结果
        List<Tenant> datas=tenantMapper.loadPagelist(tenantPage,query);

        return new PageList<>(tenantPage.getTotal(),datas);
    }

    /**
     * 入驻
     * @param dto
     */
    @Override
    public void entering(EnteringDto dto) {
        //校验
        if(dto.getMealId()==null){
            throw new GlobalException("套餐不能为空");
        }
        ValidUtils.assertNotNull(dto.getTenant(),"机构信息不能为空" );
        ValidUtils.assertNotSame(dto.getEmployee().getPassword(), dto.getComfirmPassword(), "密码不一致！");

        //登录信息 login_user //套餐 mael
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(dto.getEmployee().getUsername());
        loginUser.setPassword(dto.getEmployee().getPassword());
        loginUser.setType(0);  //最好是常量
        loginUser.setMealId(dto.getMealId());
        //链接auth服务
        AjaxResult result = loginUserClient.addOrUpdate(loginUser);
        //获取返回的loginUserId
        Long loginUserId = Long.valueOf(result.getResultObj().toString());

        //机构 tenant
        Tenant tenant = dto.getTenant();
        tenant.setRegisterTime(new Date());
        tenant.setState(0); //状态
        tenantMapper.insert(tenant);//保存
        //员工 employ
        Employee employee = dto.getEmployee();
        employee.setInputTime(new Date());//
        employee.setState(0);//状态
        employee.setTenantId(tenant.getId());
        employee.setType(5); //机构管理员
        employee.setLoginId(loginUserId); //登录信息id
        employeeMapper.insert(employee);//保存

    }
}
